package com.atguigu.tingshu.order.strategy.impl;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.Arrays;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import com.atguigu.tingshu.user.client.VipServiceConfigFeignClient;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
// vip购买策略类
public class VipOrderTradeStrategy implements OrderTradeStrategy {

    @Autowired
    private VipServiceConfigFeignClient vipServiceConfigFeignClient;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public OrderInfoVo trade(TradeVo tradeVo) {
        log.info("VipOrderTradeStrategy....trade方法执行了");

        // 构建OrderInfoVo对象
        OrderInfoVo orderInfoVo = new OrderInfoVo();

        // 根据itemId查询vip的配置信息
        Result<VipServiceConfig> serviceConfigResult = vipServiceConfigFeignClient.findById(tradeVo.getItemId());
        VipServiceConfig vipServiceConfig = serviceConfigResult.getData();

        // 设置相关的金额
        orderInfoVo.setOriginalAmount(vipServiceConfig.getPrice());
        orderInfoVo.setDerateAmount(vipServiceConfig.getPrice().subtract(vipServiceConfig.getDiscountPrice()));
        orderInfoVo.setOrderAmount(vipServiceConfig.getDiscountPrice());

        // 构建订单明细数据
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setItemId(tradeVo.getItemId());
        orderDetailVo.setItemName(vipServiceConfig.getName());
        orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
        orderDetailVo.setItemPrice((vipServiceConfig.getDiscountPrice()));
        orderInfoVo.setOrderDetailVoList(Arrays.asList(orderDetailVo));

        // 构建减免明细数据
        BigDecimal derateAmount = orderInfoVo.getDerateAmount();
        if(0 != derateAmount.intValue()) {
            OrderDerateVo derateVo = new OrderDerateVo() ;
            derateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
            derateVo.setDerateAmount(derateAmount);
            derateVo.setRemarks("vip减免明细");
            orderInfoVo.setOrderDerateVoList(Arrays.asList(derateVo));
        }
        // 给OrderInfoVo设置其他的数据(交易编号、付款项目类型、支付方式、时间戳、签名)
        this.setOther(orderInfoVo,tradeVo,redisTemplate);



        return orderInfoVo;
    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_VIP;
    }
}
